/*
 * Copyright 2007 Agile Plugins Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * 	http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.googlecode.agileplugins.monkey;

import com.intellij.codeHighlighting.HighlightDisplayLevel;
import com.intellij.codeInspection.*;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.intellij.psi.search.searches.ReferencesSearch;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NotNull;

import java.util.Collection;

public class RemoveGetInstanceInspection extends LocalInspectionTool {

    protected PsiElement getContainingElement(PsiElement element, Class requiredClass) {
        while (element != null && !(requiredClass.isAssignableFrom(element.getClass()))) {
            element = element.getParent();
        }
        return element;
    }

    @NotNull
    public String getGroupDisplayName() {
        return "PurpleMonkeyDishwasher";
    }

    @NotNull
    public String getDisplayName() {
        return "Remove Get Instance";
    }

    @NotNull
    public String getShortName() {
        return "RemoveGetInstance";
    }

    public boolean isEnabledByDefault() {
        return true;
    }

    @NotNull
    public HighlightDisplayLevel getDefaultLevel() {
        return HighlightDisplayLevel.ERROR;
    }


    public ProblemDescriptor[] checkField(@NotNull PsiField field, @NotNull InspectionManager manager, boolean isOnTheFly) {
        PsiExpression initializer = field.getInitializer();
        if (initializer != null) {
            if (checkIsTest(field.getContainingFile())) {
                String name = field.getName();
                if (name != null && name.startsWith("unique")) {
                    return new ProblemDescriptor[]{manager.createProblemDescriptor(initializer, "Unique fields cannot have an initializer", (LocalQuickFix) null,
                            ProblemHighlightType.GENERIC_ERROR_OR_WARNING)};
                }
                if (field.getModifierList().hasModifierProperty("final")) {
                    return null;
                }
                Collection<PsiReference> references = ReferencesSearch.search(field, field.getUseScope(), true).findAll();
                for (PsiReference reference : references) {
                    if (reference instanceof PsiReferenceExpression) {
                        PsiReferenceExpression psiReferenceExpression = (PsiReferenceExpression) reference;
                        PsiField psiField = (PsiField) getContainingElement(psiReferenceExpression, PsiField.class);
                        if (psiField != null) {
                            return null;
                        }

                    }
                }
                PsiExpression exp = initializer;
                if (exp instanceof PsiTypeCastExpression) {
                    PsiTypeCastExpression psiTypeCastExpression = (PsiTypeCastExpression) initializer;
                    exp = psiTypeCastExpression.getOperand();
                }
                if (isDeletableInitializer(exp)) {
                    return new ProblemDescriptor[]{manager.createProblemDescriptor(initializer, "The initializer is no longer required",
                            new RemoveGetInstanceQuickFix(), ProblemHighlightType.LIKE_DEPRECATED)};
                }
            }
        }
        return null;
    }


    private boolean checkIsTest(PsiFile containingFile) {
        return containingFile.getName().endsWith("Test.java");
//        ProjectRootManager rootManager = ProjectRootManager
//                .getInstance(containingFile.getProject());
//        ProjectFileIndex fileIndex = rootManager.getFileIndex();
//
//        return fileIndex.isInTestSourceContent(containingFile.getVirtualFile());

    }


    private boolean isDeletableInitializer(PsiElement operand) {
        if (operand instanceof PsiMethodCallExpression) {
            PsiMethodCallExpression psiMethodCallExpression = (PsiMethodCallExpression) operand;
            PsiReferenceExpression methodExpression = psiMethodCallExpression.getMethodExpression();
            PsiExpression qualifierExpression = methodExpression.getQualifierExpression();
            PsiMethod psiMethod = (PsiMethod) methodExpression.resolve();
            if (psiMethod == null) {
                return false;
            }
            if (psiMethod.getReturnType() instanceof PsiPrimitiveType) {

                return false;
            }
            PsiParameter[] parameters = psiMethod.getParameterList().getParameters();
            String name = psiMethod.getName();
            if (qualifierExpression != null && qualifierExpression.getText().equals("unique")) {
                if (parameters.length == 1 && parameters[0].getType().getCanonicalText().equals("java.lang.String") && name.equals("string")) {
                    return true;
                }
                return parameters.length == 0;
            }
            return name.equals("getInstance");
        }
        return false;
    }

    private class RemoveGetInstanceQuickFix implements LocalQuickFix {

        @NotNull
        public String getName() {
            return "Remove initializer";
        }

        public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor problemdescriptor) {
            PsiExpression exp = (PsiExpression) problemdescriptor.getPsiElement();
            try {
                exp.delete();
            } catch (IncorrectOperationException e) {
                throw new RuntimeException(e);
            }
        }

        @NotNull
        public String getFamilyName() {
            return "Remove iniializer";
        }
    }
}
